import http from '@/api/http.js'
import {isWxClient} from '@/utils/utils.js'
/**
 * 微信快速登录--微信跳转地址请求
 */
const loginWxClient = async function(obj){
	// #ifdef H5
	let params,res,ua,url,path,iswx= isWxClient();
	// 微信浏览器
	if (iswx) {
		// 检查微信快速登录状态
		// uni.setStorageSync('isLoginWxClient',true);
		let isLoginWxClient = uni.getStorageSync('isLoginWxClient');
		//http://localhost:8080/h5/
		if(isLoginWxClient){
			uni.removeStorageSync('isLoginWxClient')
			return false;
		}
		
		let code = getQueryString('code');
		let state = getQueryString('state');
		let loginWxClientStatus = uni.getStorageSync('loginWxClientStatus');
		let token = uni.getStorageSync('token');
		
		
		if(!loginWxClientStatus || !token)
		{
			
			
			if(code == '' || state == ''){
				params = {
					method:'api/v2/member/wxclient/login',
					develop:true
				};
				res = await http(params);
				if(res.status){
					path = location.href;
					uni.setStorageSync('loginWxClientPath',path);
					url = res.data.url; 
					location.href = url;
				}else{
					// 微信登录出错 不再继续执行微信快速登录
					/* uni.showToast({
						icon:'none',
						title:res.msg,
						duration:1500
					}) */
					console.log(res.msg)
					uni.setStorageSync('isLoginWxClient',true);
				}
			}else{
				if(code && state == 'wxclientlogin'){
					// 获取分销邀请人员的分销码
					let fxpcode = uni.getStorageSync('fxpcode');
						fxpcode = fxpcode ? fxpcode : '';
					// 执行微信快速登录
					let params = {
						method: 'api/v2/member/wxclient/callback',
						code,
						fxpcode
					};
					let res = await http(params);
					if(res.status)
					{
						uni.setStorageSync('token',res.data.token);
						uni.setStorageSync('userInfo',res.data.memberInfo);
						uni.setStorageSync('loginWxClientStatus',true);
						obj.$store.commit('login', res.data.memberInfo);
					}
					
					let loginWxClientPath = uni.getStorageSync('loginWxClientPath');
					if(loginWxClientPath){
						location.href = loginWxClientPath;
					}else{
						uni.showToast({
							icon:'none',
							title:'正在跳转首页',
							duration:1500
						})
						uni.switchTab({
							url:'pages/index/index'
						})
					}
					
				}else{
					uni.showToast({
						icon:'none',
						title:'回调失败',
						duration:1500
					})
					uni.setStorageSync('loginWxClientStatus',false);
				}
			}
		}
		
	} 
	// #endif
}

/**
 * [获取URL中的参数名及参数值]
 * @param {Object} name
 */
const getQueryString = function(name)
{
   var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
   var r = window.location.search.substr(1).match(reg);
   if(r!=null)
   {
	   return unescape(r[2]);
   }
   else
   {
	   return '';
   }
}

export {
	loginWxClient
}